package de.wepner.texteditor.command;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.JFileChooser;

import de.wepner.texteditor.io.IOUtils;
import de.wepner.texteditor.model.EditedFile;
import de.wepner.texteditor.model.EditorData;


/**
 * <p>Saves the currently edited file.</p>
 * <p>A parameter controls if the file chooser should be displayed
 * always ("Save as...") or if the file chooser should only be
 * displayed for created files ("Save").</p>
 * 
 * @author Richard
 */
public class SaveCommand extends Command {
    
    private final EditorData data;
    private final Component window;
    private final boolean forceFileSelect;
    
    
    public SaveCommand(EditorData data, Component window, boolean forceFileSelect) {
        this.data = data;
        this.window = window;
        this.forceFileSelect = forceFileSelect;
    }
    
    @Override
    public void actionPerformed(ActionEvent arg0) {
        EditedFile file = this.data.getEditedFile();
        if (file != null) {
            if (this.forceFileSelect || file.getFile() == null || file.isDirty()) {
                File fsFile;
                if (!this.forceFileSelect && file.getFile() != null) {
                    fsFile = file.getFile();
                } else {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setSelectedFile(file.getFile());
                    if (chooser.showSaveDialog(this.window) == JFileChooser.APPROVE_OPTION) {
                        fsFile = chooser.getSelectedFile();
                    } else {
                        fsFile = null;
                    }
                }
                
                if (fsFile != null) {
                    IOUtils.saveFile(file.getContent(), fsFile);
                    file.setFile(fsFile);
                    file.setDirty(false);
                }
            }
        }
    }
}
